package routers

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"gopkg.in/olahol/melody.v1"
)

func WebsocketRouter(r *gin.Engine) {
	// websocket
	m := melody.New()
	// 升级请求为websocket
	r.GET("/:name/ws", func(c *gin.Context) {
		err := m.HandleRequest(c.Writer, c.Request)
		if err != nil {
			panic(err.Error())
		}
	})
	// 收到信息时触发的函数
	m.HandleMessage(func(s *melody.Session, msg []byte) {
		fmt.Println("msg", string(msg))
		err := m.BroadcastFilter(msg, func(q *melody.Session) bool {
			return q.Request.URL.Path == s.Request.URL.Path
		})
		if err != nil {
			panic(err.Error())
		}
	})
}
